'''
@Author: your name
@Date: 2020-03-02 09:38:17
@LastEditTime: 2020-03-03 11:03:55
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /permcomp/comparison/views.py
'''
import os
import re
import logging
from typing import Iterable, Set

from django.shortcuts import render, HttpResponseRedirect
from django.views.generic import TemplateView
from django.urls import reverse

from comparison.forms import CompTextForm
from comparison.models import AndroidPermissions


logger = logging.getLogger(__name__)


class IndexView(TemplateView):
    """Index view contains upload function"""
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        form = CompTextForm()
        context['form'] = form
        return context

    def post(self, request, *args, **kwargs):
        form = CompTextForm(request.POST)
        if form.is_valid():
            perm_set = form.cleaned_data['perm_set']
            logger.info("GET permission set: {}".format(perm_set))
            perms_desc = form.cleaned_data['desc_text']
            permission_set = AndroidPermissions.objects.fetch_valid_permission_list(perm_set)
            valid_set, exceed_set = self.__get_valid_and_exceed_perm_set(permission_set, perms_desc)
            logger.info("VALID SET {}".format(valid_set))
            logger.info("EXCEED SET {}".format(exceed_set))
            context = {
                'form': CompTextForm(),
                'valid_permissions': valid_set,
                'exceed_permissions': exceed_set
            }
            return render(request, 'index.html', context=context)

        context = {
            'form': 'form',
            'messages': form.errors.as_json()
        }
        return render(request, 'index.html', context=context)


    def __get_valid_and_exceed_perm_set(self, permissions, text):
        valid_permissions = set()
        exceed_permissions = set()
        exceed = True
        for permission in permissions:
            if permission.alias:
                alias_pattern = re.compile(permission.alias)
                if self.__has_matched_perm_text(alias_pattern, text):
                    valid_permissions.add(permission)
                    exceed = False
            if permission.zh_name:
                zh_name_pattern = re.compile(permission.zh_name)
                if self.__has_matched_perm_text(zh_name_pattern, text):
                    valid_permissions.add(permission)
                    exceed = False
            if exceed:
                exceed_permissions.add(permission)
        return valid_permissions, exceed_permissions

    def __has_matched_perm_text(self, pattern, text):
        matched_str = re.search(pattern, text)
        if matched_str:
            return True
        return False
